<template>
  <div class="header">
    <div class="back" v-if="showArrow" @click="goBack()">
      <van-icon name="arrow-left" size="26px" />
    </div>
    <div class="font">豆瓣</div>
    <div class="inupt">
      <form action="/">
        <van-search
          v-model="value"
          placeholder="请输入搜索关键词"
          shape="round"
        />
      </form>
    </div>
    <div class="username" v-if="islogin">
      <div class="user">Hi,{{ user.username }}</div>
      <div class="logout" @click="logout" v-if="showLogout">登出</div>
    </div>
    <div class="register" @click="goto()" v-else>登录/注册</div>
  </div>
</template>

<script>
import { reactive, toRefs } from "@vue/reactivity";
import { useRouter } from "vue-router";
import { onMounted } from "@vue/runtime-core";
export default {
  name: "Header",
  props: ["showArrow","showLogout"],
  setup(props) {
    let data = reactive({
      islogin: 0,
      user: {},
    });
    const router = useRouter();
    const goBack = () => {
      router.back();
    };
    const goto = () => {
      router.push("register");
    };
    // 判断是否登录
    const init = () => {
      if (localStorage.user) {
        data.islogin = 1;
        data.user = JSON.parse(localStorage.user);
        console.log(data.user);
      } else {
        data.islogin = 0;
      }
    };
    const logout = () => {
      localStorage.removeItem("user");
      init();
    };
    onMounted(() => {
      init();
    });
    return {
      goBack,
      goto,
      ...toRefs(data),
      logout,
    };
  },
};
</script>

<style lang="less" scoped>
.header {
  display: flex;
  height: 52px;
  box-shadow: 0 1px 2px #888;
  overflow: hidden;
  .back {
    margin: auto 0;
  }
  .font {
    width: 60px;
    font-size: 24px;
    padding: 10px;
    color: rgb(66, 189, 86);
    font-weight: 600;
    padding-right: 0;
  }
  .van-search {
    padding-left: 0;
  }
  .username {
    display: flex;
    margin: auto;
    margin-right: 5px;
    font-weight: 500;
    color: rgb(13, 133, 33);
    .user {
      width: 60px;
      font-size: 16px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .logout {
      font-size: 14px;
    }
  }
  .register {
    font-size: 14px;
    color: rgb(66, 189, 86);
    margin: auto;
    font-weight: 500;
    margin-right: 5px;
  }
}
</style>